#!/usr/bin/env python
# coding=utf-8
if __name__ == '__main__':
    """ for file debug"""
    import sys_util,os
    sys_util.path.insert(0,os.path.join( os.getcwd(), '..' ))

import sys_util,os
import vavava.util

def test1(log,s=0,n=100):
    from vavava.httpclient import HttpClient
    import codecs,time
    sum = 0.0
    avarage = 0.0
    counts =0

    for i in range(s,n):
        counts += 1
        try:
            w = HttpClient()
            begein = time.clock()
            content = w.Get(r'http://auspost.com.au/track/captcha.html?ts=')
            end = time.clock()
            sum += end - begein
            avarage = sum / counts
            log.info("[%06d] sum=%f, avarage=%f"%(counts,sum, avarage))
            vavava.util.assure_path("./pic")
            file_name = "./pic/%0d.png"%i
            ff = codecs.open(file_name,"wb")
            ff.write(content)
            ff.close()
            time.sleep(0.5)
            #html = content.decode('ISO-8859-1')
            #log.info(html)
            test6(log,src_file=file_name)
        except Exception as e:
            log.error(e)

def test2():
    import os,codecs
    lines = []
    files = os.listdir("./pic")
    for f in files:
        if f.endswith(".txt"):
            filename = "./pic/%s"%f
            ff = codecs.open(filename,"r","utf8")
            line = ff.readlines()
            ff.close()
            lines.append(line)
            print(line)

def test3():
    import os
    rec = r' "C:\Program Files\Tesseract-OCR\tesseract.exe" '
    out_dir = './pic/pic_%d'
    curr_dir = os.path.abspath("./pic")
    pics = []
    files = os.listdir("./pic")
    for f in files:
        if not f.endswith(".txt"):
            pics.append(f)
    for pic in pics:
        pic_name = os.path.join(curr_dir,pic)
        cmd = "%s %s %s -l auspost "%(rec,pic_name,pic_name)
        os.system(cmd)

def test4():
    from PIL import Image

    img = Image.open('tmp.jpg') # 读入图片
    img = img.convert("RGBA")

    pixdata = img.load()

    #二值化

    for y in range(img.size[1]):
        for x in range(img.size[0]):
            if pixdata[x, y][0] < 90:
                pixdata[x, y] = (0, 0, 0, 255)

    for y in range(img.size[1]):
        for x in range(img.size[0]):
            if pixdata[x, y][1] < 136:
                pixdata[x, y] = (0, 0, 0, 255)

    for y in range(img.size[1]):
        for x in range(img.size[0]):
            if pixdata[x, y][2] > 0:
                pixdata[x, y] = (255, 255, 255, 255)

    img.save("input-black.gif", "GIF")

    #放大图像 方便识别
    im_orig = Image.open('input-black.gif')
    big = im_orig.resize((1000, 500), Image.NEAREST)

def test5(src="./pic",desc="./pic/results",
          tessdata="./tessdata",lang="auspost",
          config=r"./tessdata/configs/letters"):
    import os
    from vavava.util import assure_path
    from PIL import Image
    from vavava.tesseract import Tesseract4py
    tess = Tesseract4py(path=tessdata,lang=lang,config=config)

    curr_dir = os.path.abspath(src)
    desc_dir = os.path.abspath(desc)
    assure_path(curr_dir)
    assure_path(desc_dir)
    print(curr_dir)
    print(desc_dir)
    pics = []
    files = os.listdir(curr_dir)
    for f in files:
        pic_name = os.path.join(curr_dir,f)
        if f.endswith(".png") or f.endswith(".jpg") or f.endswith(".bmp"):
            pics.append(pic_name)


    for pic_name in pics:
        try:
            log.info("get:%s"%pic_name)
            tessercat_result = tess.img_to_string(pic_name)
            if not tessercat_result:
                log.error(pic_name)
                continue
            print(tessercat_result)
            tessercat_result = tessercat_result.replace('\n','')
            tessercat_result = tessercat_result.replace(' ','')
            tessercat_result = os.path.join(desc_dir, tessercat_result+".jpg")
            tessercat_result = os.path.abspath(tessercat_result)
            if len(tessercat_result) > 100:
                log.error(tessercat_result)
                continue
            log.info(tessercat_result)
            img = Image.open(pic_name)
            img.show()
            img.save(tessercat_result)
        except Exception as e:
            log.error(e)
            continue

def test6(log,src_file,success="./pic/result",failed="./pic/123123",
          tessdata="./tessdata",lang="auspost",
          config=r"./tessdata/configs/letters"):
    import os
    from vavava.util import assure_path,reg_helper
    from PIL import Image
    from vavava.tesseract import Tesseract4py
    try:
        assure_path(success)
        assure_path(failed)
        tess = Tesseract4py(path=tessdata,lang=lang,config=config)
        tessercat_result = tess.img_to_string(src_file)
        if not tessercat_result:
            log.warn("cannot figure out:"+src_file)
            out = os.path.split(src_file)[1]
            out = os.path.join(failed,out)
            img = Image.open(src_file)
            img.save(out)
            log.error("cannot figure out:%s,save2=%s"
                      % (src_file,out) )
        else:
            tessercat_result = tessercat_result.replace('\n','')
            tessercat_result = tessercat_result.replace(' ','')
            out = os.path.split(src_file)[1]
            out = reg_helper(text=out,reg_str=r"(?P<asdf>\d+)")[0]
            out += "_" + tessercat_result + ".png"
            out = os.path.join(success,out)
            img = Image.open(src_file)
            img.show()
            img.save(out)
            log.warn("Figure out:%s-->[%s]  save2=%s"
                     % (src_file,tessercat_result,out) )

    except Exception as e:
        log.error(e)



if __name__ == '__main__':

    import vavava.util
    log = vavava.util.initlog("./log/test1.log")
    #test1(log,685,800)
    test5(src="./pic",desc="./pic/results/",lang="eng")

